#include <stdio.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#include "esp_http_server.h"
#include "lwip/ip4_addr.h"

static const char *TAG = "MAIN";
static httpd_handle_t server = NULL;
static bool is_connected_to_wifi = false;
static bool has_wifi_credentials = false;

// 函数声明 - 添加这行
void wifi_connect_sta(const char* ssid, const char* password);

// 极简HTML页面
static const char* HTML_PAGE = 
"<!DOCTYPE html>"
"<html lang='en'>"
"<head>"
"<meta charset='UTF-8'>"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>ESP32 WiFi Setup</title>"
"<style>"
"body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }"
".container { max-width: 400px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }"
"h1 { color: #3366cc; text-align: center; margin-bottom: 20px; }"
".form-group { margin-bottom: 15px; }"
"input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 3px; box-sizing: border-box; }"
"button { background: #3366cc; color: white; border: none; padding: 10px; border-radius: 3px; cursor: pointer; width: 100%; }"
"</style>"
"</head>"
"<body>"
"<div class='container'>"
"<h1>WiFi Setup</h1>"
"<form method='post' action='/config'>"
"<div class='form-group'><input type='text' name='ssid' placeholder='WiFi Name' required></div>"
"<div class='form-group'><input type='password' name='password' placeholder='Password' required></div>"
"<button type='submit'>Connect</button>"
"</form>"
"</div>"
"</body>"
"</html>";

// 成功页面
static const char* SUCCESS_HTML = 
"<!DOCTYPE html>"
"<html lang='en'>"
"<head>"
"<meta charset='UTF-8'>"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>Setup Complete</title>"
"<style>"
"body { font-family: Arial, sans-serif; margin: 20px; background: #f0f8f0; }"
".container { max-width: 400px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); text-align: center; }"
"h1 { color: #28a745; }"
".success { background: #d4edda; color: #155724; padding: 15px; border-radius: 3px; margin: 20px 0; }"
"</style>"
"</head>"
"<body>"
"<div class='container'>"
"<h1>Success!</h1>"
"<div class='success'>WiFi configuration received.</div>"
"<p>Device will attempt to connect.</p>"
"<p><a href='/'>Back to setup</a></p>"
"</div>"
"</body>"
"</html>";

// 添加done.html页面处理（避免404错误）
static const char* DONE_HTML = 
"<!DOCTYPE html>"
"<html lang='en'>"
"<head>"
"<meta charset='UTF-8'>"
"<title>Done</title>"
"<style>body{font-family:Arial;margin:20px;text-align:center}</style>"
"</head>"
"<body>"
"<h2>Setup Complete</h2>"
"<p>Configuration finished.</p>"
"<p><a href='/'>Go back</a></p>"
"</body>"
"</html>";

// HTTP处理函数
static esp_err_t root_handler(httpd_req_t *req) 
{
    ESP_LOGI(TAG, "Serving root page");
    httpd_resp_set_type(req, "text/html");
    return httpd_resp_send(req, HTML_PAGE, HTTPD_RESP_USE_STRLEN);
}

static esp_err_t config_handler(httpd_req_t *req) 
{
    ESP_LOGI(TAG, "Processing configuration form");
    
    char content[256];
    int ret = httpd_req_recv(req, content, sizeof(content)-1);
    
    if (ret > 0) 
    {
        content[ret] = '\0';
        ESP_LOGI(TAG, "Form data: %s", content);
        
        // 解析表单数据
        char *ssid_start = strstr(content, "ssid=");
        char *password_start = strstr(content, "password=");
        
        if (ssid_start && password_start) 
        {
            ssid_start += 5; // 跳过 "ssid="
            password_start += 9; // 跳过 "password="
            
            // 提取值
            char ssid[32] = {0};
            char password[64] = {0};
            
            char *ssid_end = strchr(ssid_start, '&');
            if (ssid_end) 
            {
                strncpy(ssid, ssid_start, ssid_end - ssid_start);
                strcpy(password, password_start);
            } 
            else 
            {
                strcpy(ssid, ssid_start);
                strcpy(password, password_start);
            }
            
            // URL解码（处理+号）
            for (char *p = ssid; *p; p++) 
            {
                if (*p == '+') *p = ' ';
            }
            for (char *p = password; *p; p++) 
            {
                if (*p == '+') *p = ' ';
            }
            
            ESP_LOGI(TAG, "Parsed - SSID: '%s', Password: '%s'", ssid, password);
            
            // 保存到NVS
            nvs_handle_t nvs_handle;
            if (nvs_open("wifi_config", NVS_READWRITE, &nvs_handle) == ESP_OK) 
            {
                nvs_set_str(nvs_handle, "ssid", ssid);
                nvs_set_str(nvs_handle, "password", password);
                nvs_commit(nvs_handle);
                nvs_close(nvs_handle);
                ESP_LOGI(TAG, "Configuration saved to NVS");
                
                // 设置标志，表示有WiFi凭证
                has_wifi_credentials = true;
                
                // 尝试连接WiFi - 现在函数已经声明
                wifi_connect_sta(ssid, password);
            }
        }
        
        // 直接返回成功页面
        httpd_resp_set_type(req, "text/html");
        return httpd_resp_send(req, SUCCESS_HTML, HTTPD_RESP_USE_STRLEN);
    }
    
    return ESP_FAIL;
}

// 添加done.html处理函数
static esp_err_t done_handler(httpd_req_t *req)
{
    ESP_LOGI(TAG, "Serving done.html page");
    httpd_resp_set_type(req, "text/html");
    return httpd_resp_send(req, DONE_HTML, HTTPD_RESP_USE_STRLEN);
}

// URI配置
static const httpd_uri_t root_uri = 
{
    .uri = "/", 
    .method = HTTP_GET, 
    .handler = root_handler,
    .user_ctx = NULL
};

static const httpd_uri_t config_uri = 
{
    .uri = "/config", 
    .method = HTTP_POST, 
    .handler = config_handler,
    .user_ctx = NULL
};

static const httpd_uri_t done_uri = 
{
    .uri = "/done.html", 
    .method = HTTP_GET, 
    .handler = done_handler,
    .user_ctx = NULL
};

// 启动HTTP服务器
httpd_handle_t start_webserver(void) 
{
    httpd_handle_t server = NULL;
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    
    config.server_port = 80;
    config.stack_size = 12288;
    config.max_uri_handlers = 10;
    config.recv_wait_timeout = 10;
    config.send_wait_timeout = 10;
    config.lru_purge_enable = true;
    
    ESP_LOGI(TAG, "Starting HTTP server on port %d", config.server_port);
    
    if (httpd_start(&server, &config) == ESP_OK) {
        // 注册所有URI处理器
        httpd_register_uri_handler(server, &root_uri);
        httpd_register_uri_handler(server, &config_uri);
        httpd_register_uri_handler(server, &done_uri);  // 注册done.html处理器
        
        ESP_LOGI(TAG, "HTTP server started successfully");
        ESP_LOGI(TAG, "Registered URIs: /, /config, /done.html");
        return server;
    }
    
    ESP_LOGE(TAG, "Failed to start HTTP server");
    return NULL;
}

void wifi_connect_sta(const char* ssid, const char* password) 
{
    if (ssid == NULL || strlen(ssid) == 0) {
        ESP_LOGE(TAG, "Invalid SSID");
        return;
    }
    
    ESP_LOGI(TAG, "Connecting to WiFi: %s", ssid);
    
    // 断开现有连接
    esp_wifi_disconnect();
    vTaskDelay(100 / portTICK_PERIOD_MS);
    
    // 配置WiFi参数
    wifi_config_t wifi_config = {0};
    
    strncpy((char*)wifi_config.sta.ssid, ssid, sizeof(wifi_config.sta.ssid) - 1);
    wifi_config.sta.ssid[sizeof(wifi_config.sta.ssid) - 1] = '\0';
    if (password != NULL) 
    {
        strncpy((char*)wifi_config.sta.password, password, sizeof(wifi_config.sta.password) - 1);
        wifi_config.sta.password[sizeof(wifi_config.sta.password) - 1] = '\0';
    }
    
    // 设置连接参数
    wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
    wifi_config.sta.pmf_cfg.capable = true;
    wifi_config.sta.pmf_cfg.required = false;
    
    // ✅ 使用正确的API函数
    esp_err_t ret = esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to set WiFi config: %s", esp_err_to_name(ret));
        return;
    }
    
    // 开始连接
    ret = esp_wifi_connect();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to connect: %s", esp_err_to_name(ret));
    } else {
        ESP_LOGI(TAG, "WiFi connection initiated successfully");
    }
}
// 从NVS加载WiFi配置并连接
void load_and_connect_wifi(void) 
{
    nvs_handle_t nvs_handle;
    char ssid[32] = {0};
    char password[64] = {0};
    size_t required_size;
    
    if (nvs_open("wifi_config", NVS_READONLY, &nvs_handle) == ESP_OK) {
        if (nvs_get_str(nvs_handle, "ssid", NULL, &required_size) == ESP_OK) {
            nvs_get_str(nvs_handle, "ssid", ssid, &required_size);
            nvs_get_str(nvs_handle, "password", password, &required_size);
            nvs_close(nvs_handle);
            
            ESP_LOGI(TAG, "Found saved WiFi config: %s", ssid);
            has_wifi_credentials = true;
            
            // 尝试连接
            wifi_connect_sta(ssid, password);
            return;
        }
        nvs_close(nvs_handle);
    }
    
    ESP_LOGI(TAG, "No saved WiFi configuration found");
}

// WiFi事件处理函数
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT) 
    {
        switch (event_id) 
        {
            case WIFI_EVENT_STA_START:
                ESP_LOGI(TAG, "WiFi STA started");
                break;
                
            case WIFI_EVENT_STA_CONNECTED:
                ESP_LOGI(TAG, "WiFi connected to AP");
                break;
                
            case WIFI_EVENT_STA_DISCONNECTED:
                ESP_LOGW(TAG, "WiFi disconnected from AP");
                is_connected_to_wifi = false;
                
                // 如果有凭证，尝试重新连接
                if (has_wifi_credentials) 
                {
                    ESP_LOGI(TAG, "Attempting to reconnect...");
                    vTaskDelay(5000 / portTICK_PERIOD_MS);
                    esp_wifi_connect();
                }
                break;
                
            case WIFI_EVENT_AP_STACONNECTED:
                {
                    wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
                    ESP_LOGI(TAG, "Device connected to AP, MAC: %02x:%02x:%02x:%02x:%02x:%02x", 
                             event->mac[0], event->mac[1], event->mac[2],
                             event->mac[3], event->mac[4], event->mac[5]);
                }
                break;
                
            case WIFI_EVENT_AP_STADISCONNECTED:
                {
                    wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
                    ESP_LOGI(TAG, "Device disconnected from AP, MAC: %02x:%02x:%02x:%02x:%02x:%02x", 
                             event->mac[0], event->mac[1], event->mac[2],
                             event->mac[3], event->mac[4], event->mac[5]);
                }
                break;
        }
    } 
    else if (event_base == IP_EVENT) 
    {
        switch (event_id) {
            case IP_EVENT_STA_GOT_IP:
                {
                    ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
                    ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
                    is_connected_to_wifi = true;
                    
                    // 连接成功后，可以在这里添加其他逻辑
                    ESP_LOGI(TAG, "=== WiFi CONNECTION SUCCESS ===");
                    ESP_LOGI(TAG, "IP Address: " IPSTR, IP2STR(&event->ip_info.ip));
                    ESP_LOGI(TAG, "================================");
                }
                break;
                
            case IP_EVENT_AP_STAIPASSIGNED:
                ESP_LOGI(TAG, "Assigned IP to client");
                break;
        }
    }
}

void wifi_init_softap(void) 
{
    // 初始化网络堆栈
    esp_netif_init();
    esp_event_loop_create_default();
    
    // 创建默认的AP和STA
    esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    
    // ✅ 设置STA主机名
    if (sta_netif) {
        // 方法2.1: 固定名称
        esp_netif_set_hostname(sta_netif, "MyESP32Device");
        
        // 或者方法2.2: 基于MAC地址的动态名称
        // uint8_t mac[6];
        // esp_wifi_get_mac(WIFI_IF_STA, mac);
        // char hostname[32];
        // snprintf(hostname, sizeof(hostname), "ESP32-%02X%02X%02X", mac[3], mac[4], mac[5]);
        // esp_netif_set_hostname(sta_netif, hostname);
        
        ESP_LOGI(TAG, "STA hostname set to: %s", "MyESP32Device");
    }
    
    // 设置AP的IP地址
    esp_netif_ip_info_t ip_info;
    IP4_ADDR(&ip_info.ip, 192, 168, 4, 1);
    IP4_ADDR(&ip_info.gw, 192, 168, 4, 1);
    IP4_ADDR(&ip_info.netmask, 255, 255, 255, 0);
    
    esp_netif_dhcps_stop(ap_netif);
    esp_netif_set_ip_info(ap_netif, &ip_info);
    esp_netif_dhcps_start(ap_netif);

    // 初始化WiFi
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    // 注册事件处理器
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_AP_STAIPASSIGNED, &wifi_event_handler, NULL, NULL));

    // 配置AP参数
    wifi_config_t wifi_config_ap = {
        .ap = {
            .ssid = "ESP32_Soft",
            .password = "12345678",
            .ssid_len = strlen("ESP32_Soft"),
            .channel = 1,
            .authmode = WIFI_AUTH_WPA_WPA2_PSK,
            .max_connection = 4,
            .beacon_interval = 100
        }
    };

    // 设置WiFi模式为APSTA
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config_ap));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "WiFi AP initialized. SSID: %s", wifi_config_ap.ap.ssid);
}

void app_main(void) 
{
    ESP_LOGI(TAG, "Application starting...");
    
    // 初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_LOGI(TAG, "Erasing NVS and reinitializing");
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 初始化WiFi为AP模式
    wifi_init_softap();
    
    // 启动HTTP服务器
    server = start_webserver();
    
    // 尝试加载并连接保存的WiFi
    load_and_connect_wifi();
    
    if (server) 
    {
        ESP_LOGI(TAG, "=== SYSTEM READY ===");
        ESP_LOGI(TAG, "AP SSID: ESP32_Config");
        ESP_LOGI(TAG, "AP Password: 12345678");
        ESP_LOGI(TAG, "Web Interface: http://192.168.4.1");
        
        if (has_wifi_credentials) 
        {
            ESP_LOGI(TAG, "Status: Attempting to connect to saved WiFi");
        } 
        else 
        {
            ESP_LOGI(TAG, "Status: Waiting for WiFi configuration");
        }
        ESP_LOGI(TAG, "====================");
    }

    while(1) 
    {
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}